<?php

namespace App\Kuafu\Base\Model\Traits;

use App\Kuafu\Order\Service\OrderDb;

/**
 * 外卖分表
 */
trait KfWaiMaiSplit
{
    /*
     * 设置表后缀
     */
    public static function suffix(?int $shopId = null): self
    {
        if (is_int($shopId) && $shopId < 0) {
            $shopId = 0;
        }

        // 查融合库
        if ($shopId === null) {
            return (new static)->setSplitShopId(null);
        }

        // 查分库
        return (new static)->setSplitShopId($shopId);
    }

    // 重写表名
    public function getTable(): string
    {
        $tableName = parent::getTable();

        // 已经有后缀了，不反复加了
        if (preg_match("/^[a-zA-z_]*_\d*$/", $tableName)) {
            return $tableName;
        }

        $suffix = self::$splitShopId !== null ? $this->getSuffixByShopId() : '';
        return $tableName . $suffix;
    }

    public function getConnectionName(): string
    {
        if (!isset(self::$splitShopId) || self::$splitShopId === null) {
            return 'mysqlWaiMaiAll';
        }

        return OrderDb::orderDbConnection(self::$splitShopId, OrderDb::DB_TYPE_WAIMAI);
    }

    // 获取Model里配置的初始表名
    public function getBaseTable(): string
    {
        return parent::getTable();
    }
}
